package com.leyou.auth.controller;

import com.auth.pojo.UserInfo;
import com.auth.utils.JwtUtils;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.user.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2019-8-9
 */
@CrossOrigin
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_TOKEN = "user:token";

    /**
     * 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        // 查询用户是否存在
        User user = authService.queryUser(username, password);
        // 登录校验
        String token = this.authService.accredit(username, password,user);
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        System.out.println("token是否生成：" + token);
        // 将token写入redis中
        this.redisTemplate.opsForValue().set(KEY_TOKEN , token, 30, TimeUnit.MINUTES);
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        // CookieUtils.setCookie(request, response, prop.getCookieName(),
                //token, prop.getCookieMaxAge(), null, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户信息
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(
            //@CookieValue("LY_TOKEN")String token,
            HttpServletRequest request,
            HttpServletResponse response){
        try {
            String token = this.redisTemplate.opsForValue().get(KEY_TOKEN);
            System.out.println("用户在活动是否拿到了token：" + token);
            System.out.println("无token值，会到这里来吗?");
            if (token == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            // 从token中解析token信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
            // 解析成功要重新刷新token
            token = JwtUtils.generateToken(userInfo, this.prop.getPrivateKey(), this.prop.getExpire());
            // 将token写入redis中
            this.redisTemplate.delete(KEY_TOKEN);
            this.redisTemplate.opsForValue().set(KEY_TOKEN , token, 30, TimeUnit.MINUTES);
            // 更新cookie中的token
            //CookieUtils.setCookie(request, response, this.prop.getCookieName(), token, this.prop.getCookieMaxAge());

            // 解析成功返回用户信息
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 出现异常则，响应500
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
